package com.code.interceptors;

import com.code.consts.HeaderConstants;
import com.code.enums.CallSourceEnum;
import com.code.enums.ResultCode;
import com.code.exceptions.BusinessException;
import com.code.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * HEADER头参数校验
 * Header头参数大小写不敏感，比如参数X-Token和X-TOEKN是一个参数
 *
 * @author xiaoyaowang
 */
@Slf4j
public class HeaderParamsCheckInterceptor implements HandlerInterceptor {

//    @Resource
//    private RedisHandler redisHandler;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //TODO 待办人：lmc 待办时间：待定，待办事项：下一个版本前后端加上防重放攻击，即解除注释下面的代码
//        String nonce = request.getHeader(HeaderConstants.NONCE);
//        if (StringUtil.isEmpty(nonce)) {
//            throw new BusinessException(ResultCode.PARAM_NOT_COMPLETE);
//        }
//        String timestamp = request.getHeader(HeaderConstants.TIMESTAMP);
//        if (StringUtil.isEmpty(timestamp)) {
//            throw new BusinessException(ResultCode.PARAM_NOT_COMPLETE);
//        }
//        // 避免防重放攻击-保证客户端的时间与服务器的时间同步
//        long now = System.currentTimeMillis();
//        long clientRequestMills = Long.parseLong(timestamp);
//        //如果超过5min就属于恶意操作
//        if (now - clientRequestMills >= 300000) {
//            throw new BusinessException(ResultCode.MALICE_OPERATE_ERROR);
//        }
//        if (redisHandler.hasKey(CacheKeyEnum.VALUE_NONCE.formatKey(nonce))) {
//            throw new BusinessException(ResultCode.MALICE_OPERATE_ERROR);
//        }
//        redisHandler.set(CacheKeyEnum.VALUE_NONCE.formatKey(nonce), nonce, CacheKeyEnum.VALUE_NONCE.sec());

        String ip = IpUtil.getRealIp(request);

        if (handler instanceof HandlerMethod) {

            log.info("请求的ip：【{}】", ip);

            String callSource = request.getHeader(HeaderConstants.CALL_SOURCE);

            if (!CallSourceEnum.isValid(callSource)) {
                log.info("非法的调用来源");
                throw new BusinessException(ResultCode.PARAM_IS_INVALID);
            }

        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        // nothing to do
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // nothing to do
    }

}
